#!/usr/bin/env sh

set -e


install_karabiner() {
    path='/Applications/Karabiner-Elements.app'
    if [ ! -x "$path" ]; then
        name='Karabiner-Elements-12.10.0'

        url="https://gitee.com/accelad/keymap/raw/master/misc/$name.dmg"
        echo "AD keymap download Karabiner-Elements from $url"
        # curl -fsSL $url > "/tmp/$name.dmg"

        tmp_dir="/tmp/$(uuidgen)"
        git clone https://gitee.com/accelad/keymap.git $tmp_dir
        cp "$tmp_dir/misc/$name.dmg" "/tmp/$name.dmg"

        hdiutil attach "/tmp/$name.dmg"
        echo "AD keymap install Karabiner-Elements"
        sudo installer -pkg "/Volumes/$name/Karabiner-Elements.sparkle_guided.pkg" -target /
        hdiutil detach "/Volumes/$name"
    fi
}

install_keymap() {
    url='https://gitee.com/accelad/keymap/raw/master/karabiner.json'
    echo "AD keymap download keymap from $url"

    config_dir=~/.config/karabiner
    mkdir -p $config_dir
    # echo $config_dir

    curl -fsSL $url >"$config_dir/karabiner.json"
}

install() {
    echo 'AD keymap install begin'

    install_karabiner
    install_keymap

    echo 'AD keymap install complete'
}

startup() {
    open '/Applications/Karabiner-Elements.app'
}

show_usage() {
    echo 'AD keymap usage(https://gitee.com/accelad/keymap/blob/master/README.md):
convention:
    ctrl    -   Contrl key
    opt     -   Option key
    cmd     -   Command key
move:
    ctrl-f      move left(forward)
    ctrl-b      move right(backward)
    ctrl-p      move up(previous)
    ctrl-n      move down(next)
    ctrl-opt-f  move left by word
    ctrl-opt-b  move right by word
    ctrl-a      move to line head
    ctrl-e      move to line tail
delete:
    ctrl-h      delete left char
    ctrl-d      delete right char
    ctrl-opt-h  delete left word
    ctrl-opt-d  delete right word
    ctrl-k      delete from cursor to line tail
    ctrl-u      delete from cursor to line head
    ctrl-cmd-h  delete from cursor to line head
egg:
    ctrl-[      Esc key
    ctrl-j      Enter key
    ctrl-;      equal sign
'
}

__main() {
    install
    startup
    show_usage
}

__main
